package com.wjm.data_handle.service;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.*;



@Service
public class XMLHandleServiceImpl implements XMLHandleService {
    //The content in parameter.csv

    /**
     *
     * @param doc
     * @return
     * @throws DocumentException
     */
    public String parseXML1(Document doc)  {
        List<String> list=new ArrayList<String>(  );
//        SAXReader saxReader = new SAXReader( );
//        Document doc = saxReader.read(file);
        Element root = doc.getRootElement( );
        Element measurement = root.element("measurement");
        Element status = measurement.element("status");
        Element results=measurement.element("results");
        list.add("name,value");
        for (Iterator<Element> parameters=status.elementIterator("parameter");parameters.hasNext();) {
            Element next = parameters.next( );
            list.add(next.attributeValue("name")+","+next.getText().trim());
        }
        for (Iterator<Element> parameters=results.elementIterator("parameter");parameters.hasNext();) {
            Element next = parameters.next( );
            if(next.attributeValue("name").equals("CVG")){
                list.add("\""+next.attributeValue("caption")+","+next.getText().trim()+"\"");
                continue;
            }
            list.add(next.attributeValue("caption")+","+next.getText().trim());
        }
        String s = listToStringBuffer(list);
        return s;

    }
    //The content in wavelength.csv

    /**
     *
     * @param doc
     * @return
     * @throws DocumentException
     */
    public String parseXML2(Document doc)  {

        List<String> list=new ArrayList<String>(  );
//        SAXReader saxReader = new SAXReader( );
//        Document doc = saxReader.read(file);
        Element root = doc.getRootElement( );
        Element measurement = root.element("measurement");
        Element data = measurement.element("data");
        list.add("wavelength,value");
        for (Iterator<Element> rows=data.elementIterator("row");rows.hasNext();) {

            Element next = rows.next( );
            list.add(next.attributeValue("wavelength")+","+next.attributeValue("value"));
        }
        String s = listToStringBuffer(list);
        return s;
    }

    /**
     *
     * @param list
     * @return
     * @throws DocumentException
     */
    public String listToStringBuffer(List<String> list)  {
        StringBuffer stringBuffer = new StringBuffer( );
        for (String s:
                list) {
            stringBuffer.append(s+"\r\n");
        }
        return stringBuffer.toString();
    }
}

